package main

import (
	"boke/blogpb"
	_ "doc-sanhao-view/pkg/mysql"
	"fmt"
	"github.com/jmoiron/sqlx"
	"github.com/rs/zerolog/log"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"net"
	"os"
	"os/signal"
)

var (
	err        error
	db         *sqlx.DB
	insert_sql = "INSERT INTO `blog`.`item` (`author_id`, `content`, `title`) VALUES ( :author_id, :content, :title )"
	select_sql = ` SELECT 
    item.id, item.author_id, item.content, item.title
FROM
    blog.item
WHERE
    item.id = ?`

	update_sql = `UPDATE blog.item 
SET 
    author_id = :author_id,
    content = :content,
    title = :title
WHERE
    id = :id;
`

	delete_sql = `DELETE FROM blog.item 
WHERE
    id = ?;
`
)

func init() {
	dns := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", "zrd", "123456", "192.168.1.51", "blog")
	db, err = sqlx.Connect("mysql", dns)
	if err != nil {
		log.Error().Err(err)
	}
	err = db.Ping()
	if err != nil {
		log.Error().Err(err)
	}
}

type server struct{}

// blog 结构体
type blogItem struct {
	ID       int64  `db:"id"`
	AuthorID string `db:"author_id"`
	Content  string `db:"content"`
	Title    string `db:"title"`
}

func main() {
	lis, err := net.Listen("tcp", "0.0.0.0:50051")
	if err != nil {
		log.Panic().Err(err)
	}
	opts := []grpc.ServerOption{}
	s := grpc.NewServer(opts...)
	blogpb.RegisterBlogServiceServer(s, &server{})
	// Register reflection service on gRPC server.
	reflection.Register(s)
	go func() {
		fmt.Println("启动服务")
		if err = s.Serve(lis); err != nil {
			log.Panic().Err(err)
		}
	}()

	// 等待退出指令
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)

	// 卡住
	<-ch
	fmt.Println("Stopping the server")
	s.Stop()
	fmt.Println("Closing the listener")
	lis.Close()
	fmt.Println("Closing MySQL Connection")
	db.Close()
	fmt.Println("End of Program")
}
